<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div>Promise就是将异步转为同步，但是是通过回调函数方式书写的。</div>
    <p>采用回调函数的弊端：陷入回调地狱</p>
    <p>使用promise的语法糖，async、await把异步转为同步可以解决。</p>
    <p>await只能在async的方法中使用。</p>
    <ul>
        <li>await：把promise对象变为普通变量。</li>
        <li>async函数：返回的是一个promise对象</li>
    </ul>
    <script>
        function buy([user, food]) {
            let promise = new Promise(function (resolve, reject) {
                setTimeout(() => {
                    
                    // 买成功
                    if (Math.random() < 0.5) {
                        console.log(user, "买回了", food);
                        resolve({ user, food });
                    // 买失败
                    } else {
                        console.log(user, "没有买到", food);
                        reject({ user, food })
                    }
                }, 750);
            });
            return promise;
        }

        function eat() {
            let promise = buy(["袁浩哲", "牛肉"]);
            promise.then(res => {
                console.log(res.user, "你做得很不错，买回了", res.food, "快来吃火锅！");

                let promise2 = buy(["郑涛", "猪肉"]);
                promise2.then(res => {
                    console.log(res.user, "你做得很不错，买回了", res.food, "快来吃火锅！");
                })
            })
        }


        async function eat2() {
            let res = null;
            try {
                res = await buy(["袁浩哲", "牛肉"]);
                console.log(res.user, "你做得很不错，买回了", res.food, "快来吃火锅！");
            } catch (e) {
                console.log(e.user, "连", e.food, "都没有买到，你好意思回来，出去！");
            }
            try {
                res = await buy(["郑涛", "猪肉"]);
                console.log(res.user, "你做得很不错，买回了", res.food, "快来吃火锅！");
            } catch (e) {
                console.log(e.user, "连", e.food, "都没有买到，你好意思回来，出去！");
            }

            try {
                res = await buy(["子措", "鸡肉"]);
                console.log(res.user, "你做得很不错，买回了", res.food, "快来吃火锅！");
            } catch (e) {
                console.log(e.user, "连", e.food, "都没有买到，你好意思回来，出去！");
            }
            return {msg: "吃完了"}
        }

        // async函数的返回结果，直接使用普通方式无法获取，需要以promise对象的方式获取
        // let res = eat2();
        // console.log(res);

        eat2().then(res => {
            console.log(res)
        });


    </script>
</body>

</html>